package demo;
/**
 *  双向链表实现队列
 */
public class MyQueue {
    static class ListNode {
        public int val;
        public ListNode prev;
        public ListNode next;
        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode head;
    public ListNode last;
    /**
     * 入队
     */
    public void offer(int val) {
        ListNode node = new ListNode(val);

        if(isEmpty()) {
            head = node;
            last = node;
            return;
        }
        last.next = node;
        node.prev = last;
        last = node;
    }
    /**
     * 出队(删除)
     */
    public int poll() {
        int val = 0;
        if(isEmpty()) {
            throw new EmptyException("队列为空");
        }else if(head == last) {
           val = head.val;
            head = null;
            last = null;
        }else {
            val = head.val;
            head = head.next;
            head.prev = null;
        }
        return val;
    }
    /**
     * 出队(不删除)
     */
    public int peek() {
        int val = 0;
        if(isEmpty()) {
            throw new EmptyException("队列为空");
        }
        return head.val;
    }
    /**
     * 判空
     */
    public boolean isEmpty() {
        return head == null;
    }
}
